package com.hsy.linemoney.modules.main;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.os.Handler;
import android.os.Message;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.deparse.dpframe.tools.utils.DPLogUtil;
import com.deparse.dpframe.ui.android.app.activity.DPBaseActivity;
import com.deparse.dpframe.ui.android.app.activity.DPBaseActivityWithSimpleActionBar;
import com.deparse.dpframe.ui.android.app.fragment.DPBaseFragment;
import com.deparse.dpframe.ui.android.view.DPTabItemContainer;
import com.hsy.linemoney.R;
import com.hsy.linemoney.apiservice.AccountService;
import com.hsy.linemoney.apiservice.BankService;
import com.hsy.linemoney.apiservice.CountryService;
import com.hsy.linemoney.apiservice.LineMoneyContext;
import com.hsy.linemoney.apiservice.PaymentService;
import com.hsy.linemoney.apiservice.RecurringService;
import com.hsy.linemoney.common.Consts;
import com.hsy.linemoney.modules.auth.activity.LoginActivity;
import com.hsy.linemoney.modules.common.LocalSetActivity;
import com.hsy.linemoney.modules.exchange.ExchangeHomeFragment;
import com.hsy.linemoney.modules.exchange.ExchangeOnceFragment;
import com.hsy.linemoney.modules.home.HomeFragment;
import com.hsy.linemoney.modules.main.actionbar.ExchangeActionBar;
import com.hsy.linemoney.modules.main.actionbar.HomeActionBar;
import com.hsy.linemoney.modules.main.actionbar.IActionBar;
import com.hsy.linemoney.modules.main.actionbar.MyActionBar;
import com.hsy.linemoney.modules.main.actionbar.TenderActionBar;
import com.hsy.linemoney.modules.my.MyFragment;
import com.hsy.linemoney.modules.tender.TenderFragment;

import java.lang.reflect.InvocationTargetException;

public class MainActivity extends DPBaseActivityWithSimpleActionBar {

    private static boolean isExit = false;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    private int currentIndex = 0;
    private View currentActionBar;
    private DPTabItemContainer tabs;
    private int fromCurrency = -1, toCurrency = -1;
    private String exchangeAmount;

    public void showLoginDialog() {
        final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
        builder.setCancelable(true);

        LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
        View view = layoutInflater.inflate(R.layout.dialog_exit, null);
        TextView msg = (TextView) view.findViewById(R.id.message);
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        TextView ok = (TextView) view.findViewById(R.id.ok);
        builder.setView(view);

        msg.setText(R.string.txt_please_login_first);
        cancel.setText(R.string.txt_cancel);
        ok.setText(R.string.txt_ok);

        final Dialog dialog = builder.create();

        cancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
            }
        });
        ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityWithTaskCleared(LoginActivity.class);
                dialog.dismiss();
            }
        });

        dialog.show();

    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            final Dialog builder = new AlertDialog.Builder(MainActivity.this).create();
            builder.setCancelable(true);
            builder.show();
            LayoutInflater layoutInflater = LayoutInflater.from(MainActivity.this);
            View view = layoutInflater.inflate(R.layout.dialog_exit, null);
            TextView cancel = (TextView) view.findViewById(R.id.cancel);
            TextView ok = (TextView) view.findViewById(R.id.ok);
            builder.setContentView(view);

            cancel.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.dismiss();
                }
            });
            ok.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    builder.dismiss();
                    LineMoneyContext.logout();
                    finishAllActivities();

                }
            });
            return false;
        }
        return super.onKeyDown(keyCode, event);

    }

    public void setCurrentTab(int index) {
        currentIndex = index;
        tabs.setCurrentTab(index);
    }

    private Class<?>[] fragments = {
            HomeFragment.class,
            ExchangeHomeFragment.class,
            TenderFragment.class,
            MyFragment.class
    };

    private Class<?>[] actionbars = {
            HomeActionBar.class,
            ExchangeActionBar.class,
            TenderActionBar.class,
            MyActionBar.class

    };

    private DPBaseFragment currentFragment;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (!LineMoneyContext.isLocalSetted()) {
            startActivityForResult(LocalSetActivity.class, 0);
        }

        LineMoneyContext.changeLocalLanguage(LineMoneyContext.getLocalLanguagePair());

        super.setContentView(R.layout.activity_main);

        setStausBarBackgroundColor(getResources().getColor(R.color.color_action_bar_bg));

        String key = null;
        if (null != getActivityStartExtra() && 0 != getActivityStartExtra().length) {
            key = getActivityStartExtra()[0];
        }

//        getRootView().setBackgroundColor(getResources().getColor(R.color.background_all_fragment));

        tabs = F(R.id.tabs);
        tabs.setClickable(true);
        tabs.setTabChangedEnable(LineMoneyContext.isLocalSetted() && LineMoneyContext.isLoggedIn());
        tabs.setOnTabChangeListener(new DPTabItemContainer.OnTabChangeListener() {
            @Override
            public void beforeTabChange(int index, View tabWidget) {
                if (index == 1) {
                    fromCurrency = -1;
                    toCurrency = -1;
                }
            }

            @Override
            public void afterTabChange(int index, View tabWidget) {
                try {
                    View actionBar = (View) actionbars[index].getConstructor(Context.class).newInstance(MainActivity.this);
                    setActionBar(actionBar);
                    currentActionBar = actionBar;
                    if (actionBar instanceof IActionBar) {
                        ((IActionBar) actionBar).setActivity(MainActivity.this);
                    }
                    currentFragment = (DPBaseFragment) fragments[index].newInstance();
                    currentFragment.setAttchedActivity(MainActivity.this);
                    replaceFragment(R.id.container, currentFragment);
                    currentIndex = index;
                } catch (InstantiationException e) {
                    e.printStackTrace();
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                } catch (NoSuchMethodException e) {
                    e.printStackTrace();
                } catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        });

        tabs.setOnTabClickListener(new DPTabItemContainer.OnTabClickListener() {
            @Override
            public void onTabClick(int i, View view) {
                if (i > 0 && !LineMoneyContext.isLoggedIn()) {
                    showLoginDialog();
                }
            }
        });

        if (Consts.Keys.TENDER.equals(key)) {
            tabs.setCurrentTab(2);
        } else {
            tabs.setCurrentTab(0);
        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        if (LineMoneyContext.isLoggedIn()) {
            new BankService().getBankList(null, true);
            new PaymentService().getPaymentType(null, true);
            new AccountService().getAccounts(null, true);
            new RecurringService().getRecurringType(null, true);
            new CountryService().getCountries(null, true);
        }
    }

    @Override
    protected void onStop() {
        super.onStop();
//        if (LineMoneyContext.isLoggedIn()) {
//            new BankService().getBankList(null, true);
//            new PaymentService().getPaymentType(null, true);
//            new AccountService().getAccounts(null, true);
//            new RecurringService().getRecurringType(null, true);
//            new CountryService().getCountries(null, true);
//        }
    }

    public DPBaseFragment getCurrentFragment() {
        return currentFragment;
    }

    public DPTabItemContainer getTabs() {
        return tabs;
    }

    public void setExchangeWay(int from, int to) {
        this.fromCurrency = from;
        this.toCurrency = to;
    }

    public int getExchangeFrom() {
        return fromCurrency;
    }

    public void setExchangeFrom(int from) {
        fromCurrency = from;
    }

    public int getExchangeTo() {
        return toCurrency;
    }

    public void setExchangeTo(int to) {
        toCurrency = to;
    }

    public void setExchangeAmount(String exchangeAmount) {
        this.exchangeAmount = exchangeAmount;
    }

    public String getExchangeAmount() {
        return exchangeAmount;
    }
}
